﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;

namespace ThridGroup.ERP.RBAC
{
    /// <summary>
    /// 权限接口实现  ---tsh
    /// </summary>
    public class PermissionServices : ApplicationService,IPermissionServices
    {
        private readonly IRepository<Permission> _permissionRepository;

        public PermissionServices(IRepository<Permission> permissionRepository)
        {
            _permissionRepository = permissionRepository;
        }

        /// <summary>
        /// 添加权限     ---tsh
        /// </summary>
        /// <param name="permission">实体</param>
        /// <returns>受影响行数</returns>
        public async Task<int> AddPermission(Permission permission)
        {
            try
            {
                var result = await _permissionRepository.InsertAsync(permission);
                return result != null ? 1 : 0;
            }
            catch (Exception ex)
            {
                throw new Exception($"添加权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除权限     ---tsh
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>受影响行数</returns>
        public async Task<int> DelPermission(Permission permission)
        {
            try
            {
                await _permissionRepository.DeleteAsync(x=>x.Id==permission.Id);
                return 1;
            }
            catch (Exception ex)
            {
                throw new Exception($"删除权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改权限    ---tsh
        /// </summary>
        /// <param name="permission">实体</param>
        /// <returns>受影响行数</returns>
        public async Task<int> UpdPermission(Permission permission)
        {
            try
            {
                var existingPermission = await _permissionRepository.FindAsync(x => x.Id == permission.Id);
                if (existingPermission == null)
                {
                    return 0;
                }

                await _permissionRepository.UpdateAsync(permission);
                return 1;
            }
            catch (Exception ex)
            {
                throw new Exception($"修改权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查询权限     ---tsh
        /// </summary>
        /// <returns>集合</returns>
        public IQueryable<Permission> QueryPermission()
        {
            try
            {
                return _permissionRepository.GetQueryableAsync().Result.AsQueryable();
            }
            catch (Exception ex)
            {
                throw new Exception($"查询权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取权限树形数据
        /// </summary>
        /// <returns>权限树形结构</returns>
        public async Task<List<PermissionTreeDto>> GetPermissionTree()
        {
            try
            {
                var permissions = await _permissionRepository.GetListAsync();
                var tree = BuildPermissionTree(permissions, 0);
                return tree;
            }
            catch (Exception ex)
            {
                throw new Exception($"获取权限树形数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 构建权限树形结构
        /// </summary>
        /// <param name="permissions">所有权限</param>
        /// <param name="parentId">父级ID</param>
        /// <returns>权限树</returns>
        private List<PermissionTreeDto> BuildPermissionTree(List<Permission> permissions, int parentId)
        {
            var tree = new List<PermissionTreeDto>();
            var children = permissions.Where(x => x.FatherPermissionId == parentId).OrderBy(x => x.OrderId).ToList();

            foreach (var permission in children)
            {
                var node = new PermissionTreeDto
                {
                    Id = permission.Id,
                    Title = permission.PermissionName,
                    Checked = false,
                    Children = BuildPermissionTree(permissions, permission.Id)
                };
                tree.Add(node);
            }

            return tree;
        }

        /// <summary>
        /// 根据ID获取单个权限
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns>权限信息</returns>
        public async Task<Permission> GetPermissionById(int id)
        {
            try
            {
                return await _permissionRepository.FindAsync(x => x.Id == id);
            }
            catch (Exception ex)
            {
                throw new Exception($"获取权限信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取权限详细信息（用于表单回填）
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns>权限详细信息</returns>
        public async Task<PermissionDetailDto> GetPermissionDetailById(int id)
        {
            try
            {
                var permission = await _permissionRepository.FindAsync(x => x.Id == id);
                if (permission == null)
                {
                    return null;
                }

                var detail = new PermissionDetailDto
                {
                    Id = permission.Id,
                    PermissionName = permission.PermissionName ?? "",
                    FatherPermissionId = permission.FatherPermissionId,
                    PermissionPath = permission.PermissionPath ?? "",
                    OrderId = permission.OrderId,
                    PermissionImg = permission.PermissionImg ?? "",
                    PermissionState = permission.PermissionState
                };

                // 获取父级权限名称
                if (permission.FatherPermissionId > 0)
                {
                    var fatherPermission = await _permissionRepository.FindAsync(x => x.Id == permission.FatherPermissionId);
                    detail.FatherPermissionName = fatherPermission?.PermissionName ?? "未知父级权限";
                }
                else
                {
                    detail.FatherPermissionName = "根级权限";
                }

                return detail;
            }
            catch (Exception ex)
            {
                throw new Exception($"获取权限详细信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有权限列表
        /// </summary>
        /// <returns>权限列表</returns>
        public async Task<List<Permission>> GetAllPermissions()
        {
            try
            {
                return await _permissionRepository.GetListAsync();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取权限列表失败: {ex.Message}");
            }
        }
    }
}
